<!--  -->
<template>
  <div class='padding20 myExper'>
    <h3>我的实验</h3>
    <div class="buttonList">
      <el-checkbox-group v-model="buttonValue" @change='buttonValueChange'>
        <el-checkbox-button label="">全部</el-checkbox-button>
        <el-checkbox-button label="2">进行中</el-checkbox-button>
        <el-checkbox-button label="1">待审批</el-checkbox-button>
        <el-checkbox-button label="3">驳回</el-checkbox-button>
        <el-checkbox-button label="4">已完成</el-checkbox-button>
      </el-checkbox-group>
    </div>
    <div class="search">
      <FormSearch ref="searchFrom" :formItem="searchItem" :formData.sync="searchData" :buttonList="buttonAll.searchList" @clearForm="clearForm" @searchData="getPage" />
    </div>
    <div class="content search">
      <div style="display:flex; flex-wrap:wrap;justify-content:space-between">
        <el-card v-for='(it,index) in content' :key='index' style="width:24%;margin-bottom:20px">
          <div class="pointer" v-if='it.first' style="text-align:center;display: flex; flex-direction: column; align-items: center; justify-content: center; height: 181px"  @click="goNewExper">
            <img src='static/B1/experMenu/plus.svg' style="width: 50px;height: 50px;margin-bottom: 20px;">
            <el-button type="primary">新建实验</el-button>
          </div>
          <div v-else>
            <div class="top pointer" style="display:flex" @click="goDetail(it)">
              <div class="left font20" style="width:68px;text-align:center;margin-right:15px;background: rgb(229,229,229);border-radius: 10px;padding:5px;min-height:108px;display:flex;align-items:center">{{stateType[it.expGroup -1]}}</div>
              <div class="right" style="flex:1">
                <div class="title font18">{{it.expName}}</div>
                <div class="des" style="color: #989898">说明：{{it.remark}}</div>
              </div>
            </div>
            <div class="bottom font12" style="margin-top:10px; border-top: 1px solid #ebebeb; display:flex;padding:10px;justify-content:space-between;padding-top:20px;padding-bottom:0">
              <div class="bot-left">
                <span style="width: 6px;height:6px; display:inline-block;border-radius:50%" :style="{background:it.state=='3'?'#f04134':it.state=='2'?'#ffaa00':'#108de9'}"></span>
                <span>{{ it.checkState == '3' ? '已驳回' :  ['',"待审批", "进行中", '', '已完成'][it.state]}}</span>
                <!-- state： 1（创建、待审批） 2（进行中） 4（已完成） -->
                <!-- checkState： 1待审核 2通过 3驳回 -->
                <span>{{it.startTime}}</span>
              </div>
              <div class="bot-right">
                <el-button v-if="it.isStart==2 && it.state == '2'" type="primary" style="margin-right:20px" size='small' @click='experOperate(it, "开启")'>开启实验</el-button>
                <el-button v-if='it.isStart==1 && it.state == 2' type="danger" style="margin-right:20px" size='small' @click='experOperate(it, "结束")'>结束实验</el-button>
                <el-dropdown @command='dropItemClick'>
                  <span> <i class="el-icon-more"></i></span>
                  <el-dropdown-menu slot='dropdown'>
                    <div v-if='it.checkState == 3'>
                      <el-dropdown-item :command='composeValue("apply", it)'>申请资源</el-dropdown-item>
                    </div>
                    <div v-if='it.state == 1 && it.checkState != 3'>
                      <el-dropdown-item :command='composeValue("approve", it)'>催批</el-dropdown-item>
                    </div>
                    <div v-if='it.state==2'>
                      <el-dropdown-item :command='composeValue("resouceDownload", it)'>下载资源</el-dropdown-item>
                      <el-dropdown-item :command='composeValue("submit", it)'>成果提交</el-dropdown-item>
                      <el-dropdown-item :command='composeValue("resultDownload", it)'>成果下载</el-dropdown-item>
                    </div>
                    <el-dropdown-item :command='composeValue("delete", it)'>删除</el-dropdown-item>
                  </el-dropdown-menu>
                </el-dropdown>
              </div>
            </div>
          </div>
        </el-card>
        <div style="width:24%;margin-bottom:20px;height:0" v-for='n in 6' :key='n'></div>
      </div>
    </div>
    <DialogView v-if="title" style="margin-left:20%;" :title-text="title" :appendToBody="true" :btnShow="false" width-num="70%" @close="title=''">
      <template v-slot:main>
        <div class='margintb'>
          <div>数据资源</div>
          <Table class='margintb' :list="resultList.filter(it=>it.resType == 1)" :title-list="titleList">
            <template v-slot:[it.prop]="prop" v-for="(it, index) in titleList.filter((it) => it.slot)">
              <span :key="index">
                <span v-if="it.prop == 'operate'">
                  <el-button type="text" @click="resourceDownload(prop)">下载</el-button>
                </span>
                <span v-if="it.prop == 'index'">
                  {{prop.index +1}}
                </span>
              </span>
            </template>
          </Table>
        </div>
        <div class="margintb">
          <div>模型资源</div>
          <Table class='margintb' :list="resultList.filter(it=>it.resType == 2)" :title-list="titleList">
            <template v-slot:[it.prop]="prop" v-for="(it, index) in titleList.filter((it) => it.slot)">
              <span :key="index">
                <span v-if="it.prop == 'operate'">
                  <el-button type="text" @click="resourceDownload(prop)">下载</el-button>
                </span>
                <span v-if="it.prop == 'index'">
                  {{prop.index +1}}
                </span>
              </span>
            </template>
          </Table>
        </div>
        <div class="margintb">
          <div>硬件资源</div>
          <Table class='margintb' :list="resultList.filter(it=>it.resType == 3)" :title-list="titleList">
            <template v-slot:[it.prop]="prop" v-for="(it, index) in titleList.filter((it) => it.slot)">
              <span :key="index">
                <span v-if="it.prop == 'operate'">
                  <el-button type="text" @click="resourceDownload(prop)">下载</el-button>
                </span>
                <span v-if="it.prop == 'index'">
                  {{prop.index +1}}
                </span>
              </span>
            </template>
          </Table>
        </div>
      </template>
    </DialogView>
    <DialogView v-if="resultSubmit" style="margin-left:20%; height:800px;overflow:auto" :title-text="resultSubmit" :appendToBody="true" @save="submitResult" width-num="70%" @close="resultClose">
      <template v-slot:main>
        <FormSearch style='marginLeft:30%' ref="resultFrom" :formItem="resultItem" :formData.sync="resultData" :isInLine="false" @upload="upload" />
      </template>
    </DialogView>
  </div>
</template>

<script>
import util from "./components/util.js";
import experApi from "../api/exper.service";
export default {
  components: {},
  data() {
    return {
      ...util.getExper(),
      buttonValue: [""],
      content: [],
      title: "",
      stateType: [],
      resultSubmit: "",
      // resultList中的resType是1 2 3？，接口有0
      resultList: [],
      originSearhData: {},
      isResultAlreadyAdd: false,
      fileExpName: '',
      expId: ''
    };
  },
  mounted() {
    this.originSearhData = JSON.parse(JSON.stringify(this.searchData));
    this.getPage();
    this.experType();
  },
  computed: {},
  watch: {},
  methods: {
    async experType() {
      let { data } = await experApi.experType();
      this.searchItem.find(it => it.prop == "expGroup").list = data.map(it => {
        return {
          label: it.label,
          id: it.value
        };
      });
      this.stateType = data.map(it => {
        return it.label;
      });
    },
    async getPage() {
      console.log(this.searchData)
      let { data } = await experApi.getPage(
        this.$funUtil.filterObjAttribute(this.searchData, "time")
      );
      this.content = [
        {
          first: true
        }
      ].concat(data.records);
      console.log(this.content)
    },
    buttonValueChange(val) {
      this.buttonValue = [val.pop()];
      // 1请求的是checkState 审核状态为待审批    3为驳回 
      if (this.buttonValue[0] == 1 || this.buttonValue[0] == 3) {
        this.searchData.state = '';
        this.searchData.checkState = this.buttonValue[0];
      } else {
        // 2为state 进行中   4为已完成
        this.searchData.state = this.buttonValue[0];
        this.searchData.checkState = '';
      }
      this.getPage();
    },
    clearForm() {
      this.$refs.searchFrom.$refs.formSearch.resetFields();
      this.searchData = JSON.parse(JSON.stringify(this.originSearhData));
      this.buttonValue = [""];
      this.getPage();
    },
    resultClose() {
      this.resultSubmit = "";
      this.$refs.resultFrom.$refs.formSearch.resetFields();
    },
    // 新建实验
    goNewExper() {
      this.$router.push("/scienceExper/views/threatTracing/experiment/newExper");
    },
    goDetail(it) {
      this.$router.push({
        path: "/scienceExper/views/threatTracing/experiment/experDetail",
        query: {
          id: it.id
        }
      });
    },
    composeValue(value, it) {
      return {
        value,
        it
      };
    },
    dropItemClick(item) {
      // console.log(item, "ii");
      switch (item.value) {
        case "apply":
          this.$router.push({
            path: "/scienceExper/views/threatTracing/experiment/applyResources",
            query: {
              id: item.it.id
            }
          });
          break;
        case "approve":
          this.approve(item.it.id)
          break;
        case "resouceDownload":
          this.title = "资源下载列表";
          this.fileExpName = item.it.expName;
          this.selectResource(item.it.id);
          break;
        case "submit":
          this.resultSubmit = "成果提交";
          if (item.it.result) {
            this.getResult(item.it.id);
            this.isResultAlreadyAdd = true;
          } else {
            this.resultData.id = "";
            this.isResultAlreadyAdd = false;
          }
          this.resultData.expId = item.it.id;
          break;
        case "resultDownload":
          this.resultDownload(item.it.id, item.it.expName)
          break;
        case "delete":
          this.deleteExper(item.it.id);
          break;
      }
    },
    // 成果下载
    async resultDownload(id, expName) {
      let data = await experApi.resultDownload(id, expName)
    },
    // 下载资源
    async resourceDownload(item) {
      // console.log(item.data)
      let data = await experApi.resourceDownload(item.data.expId, this.fileExpName + '-' + item.data.name)
    },
    async deleteExper(id) {
      let data = await experApi.deleteExper(id);
      if (data.code == 10200) {
        this.$message.success("删除实验成功");
        this.getPage();
      }
    },
    async approve(id) {
      let data = await experApi.approve(id)
      if (data.code === 10200) {
        this.$message.success('催批成功')
      }
    },
    async selectResource(v) {
      let { data } = await experApi.selectResource({ id: v });
      this.resultList = data;
    },
    upload(data) {
      this.resultFile = data
    },
    async uploadFn() {
      let formdata = new FormData();
      formdata.append("netExcel", this.resultFile);
      formdata.append("expId", this.resultData.expId);
      let { data } = await experApi.resultUpload(formdata);
      console.log(data.data)
      if(data.code == 10200) {
        this.resultData.resultFile = data.data.path
        this.resultData.fileName = data.data.file
        this.submitData()
      }
    },
    async submitData() {
      let data = this.isResultAlreadyAdd
        ? await experApi.resultUpdate(this.resultData)
        : await experApi.resultAdd(this.resultData);
      console.log(data, "ddd");
      if (data.code == 10200) {
        this.$message.success(data.data);
        this.resultSubmit = "";
      } else {
        this.$message.error(data.data);
      }
    },
    async submitResult() {
      // console.log(this.resultData)
      if (this.resultFile) {
        this.uploadFn()
      } else {
        this.submitData()
      }
      /* let data = this.isResultAlreadyAdd
        ? await experApi.resultUpdate(this.resultData)
        : await experApi.resultAdd(this.resultData);
      console.log(data, "ddd");
      if (data.code == 10200) {
        this.$message.success(data.data);
        this.resultSubmit = "";
      } else {
        this.$message.error(data.data);
      } */
    },
    async getResult(id) {
      let { data } = await experApi.getResult(id);
      this.resultData = data;
    },
    // 开启实验
    async experOperate(it, value) {
      if (value == "结束") {
        it.state = 4;
      } else {
        it.isStart = 1;
      }
      let data = await experApi.updateExp(it);
      if (data.code == 10200) {
        this.$message.success("实验" + value + "成功");
        this.getPage();
      }
    }
  },
  created() {}
};
</script>
<style lang='less' scoped>
.myExper {
  /deep/ .el-form-item__label {
    font-size: 16px;
  }
  /deep/ .el-card__body,
  .el-main {
    padding: 10px;
  }
  font-size: 16px;
  .search {
    margin-top: 10px;
  }
}
</style>
<style lang="less">
.el-card__body{
  height: 100%;
}
</style>
